// import { login, logout, getAuthMenu } from '@/api/user'
import { login, logout, treeList } from '@/api/user'
import { getToken, setToken, removeToken, setUserId, getUserId, getUserName, setUserName } from '@/utils/auth'
import router, { resetRouter } from '@/router'
export function getWriteChildNode(data, newArr = []) {
    for (var i = 0; i < data.length; i++) {
        if (data[i].child !== undefined) {
            getWriteChildNode(data[i].child, newArr)
        } else {
            newArr.push(data[i])
        }
    }
    return newArr
}

const state = {
    token: getToken(),
    userId: getUserId(),
    name: getUserName(),
    roles: []
}

const mutations = {
    SET_TOKEN: (state, token) => {
        state.token = token
    },
    SET_USERID: (state, userId) => {
        state.userId = userId
    },
    SET_NAME: (state, name) => {
        state.name = name
    },
    SET_ROLES: (state, roles) => {
        state.roles = roles
    }

}

const actions = {
    // user login
    login({ commit }, userInfo) {
        const { username, password } = userInfo
        return new Promise((resolve, reject) => {
            login({ userAcct: username.trim(), userPwd: password })
                .then(response => {
                    console.log(response);
                    commit('SET_USERID', response.data.data.Userinfo.Userid)
                    commit('SET_TOKEN', response.headers.usertoken)
                    commit('SET_NAME', response.data.data.Userinfo.Username)
                    setUserName(response.data.data.Userinfo.Username)
                    setUserId(response.data.data.Userinfo.Userid)
                    setToken(response.headers.usertoken)
                    resolve()
                })
                .catch(error => {
                    console.log(error, 'ppp')
                    reject(error)
                })
        })
    },

    // get user info
    getInfo({ commit, state }) {
        return new Promise((resolve, reject) => {
            const params = {}
            params.username = state.name
            treeList(params).then(response => {
                console.log(response);
                if (!response.data.data) {
                    reject('登录异常，请重新操作')
                }
                // const rolesList = getWriteChildNode(response.data, [])
                // const newOneRolesList = []
                // rolesList.forEach(info => {
                //   newOneRolesList.push(info.url)
                // })
                // const obj = {
                //   roles: newOneRolesList.length > 0 ? [...newOneRolesList, '99999'] : ['1', '99999']
                // }
                var array1 = [{
                    id: 1,
                    name: '后台管理',
                    url: null,
                    pid: 0,
                    icon: null,
                    child: [{
                            id: 26,
                            name: '基本信息',
                            url: '/basicInfo',
                            pid: 1,
                            icon: 'guide',
                            title: 'guide',
                            child: [
                                { id: 41, name: '代理商管理', url: '/basicInfo/agentManagement', pid: 26, title: 'agentManagement', icon: '' },
                                { id: 41, name: '学校管理', url: '/basicInfo/schoolManagement', title: 'schoolManagement', pid: 26, icon: '' }
                            ]
                        },
                        {
                            id: 26,
                            name: '教务管理',
                            url: '/educationalManagement',
                            pid: 1,
                            icon: 'clipboard',
                            title: 'guide',
                            child: [
                                { id: 41, name: '教师管理', url: '/educationalManagement/teacherManagement', pid: 26, title: 'teacherManagement', icon: '' },
                                { id: 41, name: '班级管理', url: '/educationalManagement/classManagement', pid: 26, title: 'classManagement', icon: '' },
                                { id: 41, name: '年级管理', url: '/educationalManagement/gradeManagement', pid: 26, title: 'classManagement', icon: '' },
                                { id: 41, name: '学生管理', url: '/educationalManagement/studentManagement', pid: 26, title: 'studentManagement', icon: '' },
                                { id: 41, name: '课程表', url: '/educationalManagement/courseManagement', pid: 26, title: 'courseManagement', icon: '' },
                                { id: 41, name: '科目信息', url: '/educationalManagement/subjectInfo', pid: 26, title: 'subjectInfo', icon: '' }
                            ]
                        },
                        {
                            id: 26,
                            name: '学生证管理',
                            url: '/studentCard',
                            pid: 1,
                            icon: 'documentation',
                            title: 'studentCard',
                            child: [
                                { id: 41, name: '设备出入库信息', url: '/studentCard/deviceInfo', pid: 26, title: 'deviceInfo', icon: '' },
                                { id: 41, name: '学生证信息', url: '/studentCard/studentCardInfo', pid: 26, title: 'studentCardInfo', icon: '' },
                                { id: 41, name: '通话记录', url: '/studentCard/callLog', pid: 26, title: 'callLog', icon: '' }
                            ]
                        },
                        {
                            id: 26,
                            name: '会议管理',
                            url: '/meetingManagement',
                            pid: 1,
                            icon: 'star',
                            title: 'meetingManagement',
                            child: [
                                { id: 41, name: '会议设备', url: '/meetingManagement/meetingDevice', title: 'meetingDevice', pid: 26, icon: '' },
                                { id: 41, name: '会议管理', url: '/meetingManagement/meetingAdmin', pid: 26, title: 'meetingAdmin', icon: '' },
                                // { id: 41, name: '会议签到统计', url: '/meetingManagement/meetingStatistics', pid: 26, title: 'meetingStatistics', icon: '' },
                                { id: 41, name: '会议签到记录', url: '/meetingManagement/meetingRecord', pid: 26, title: 'meetingRecord', icon: '' }
                            ]
                        },
                        {
                            id: 26,
                            name: '道闸通行管理',
                            url: '/roadGateManagement',
                            pid: 1,
                            icon: 'money',
                            title: 'roadGateManagement',
                            child: [
                                { id: 41, name: '道闸设备', url: '/roadGateManagement/roadGateDevice', pid: 26, title: 'roadGateDevice', icon: '' },
                                { id: 41, name: '通行规则', url: '/roadGateManagement/throughManagement', pid: 26, title: 'throughManagement', icon: '' },
                                { id: 41, name: '通行记录', url: '/roadGateManagement/throughRecord', pid: 26, title: 'throughRecord', icon: '' }
                            ]
                        },
                        // {
                        //     id: 26,
                        //     name: '考勤管理',
                        //     url: '/checkWorkManagement',
                        //     pid: 1,
                        //     icon: 'chart',
                        //     title: 'checkWorkManagement',
                        //     child: [
                        //         { id: 41, name: '考勤设备', url: '/checkWorkManagement/checkWorkDevice', pid: 26, title: 'checkWorkDevice', icon: '' },
                        //         { id: 41, name: '考勤规则', url: '/checkWorkManagement/checkWorkRule', pid: 26, title: 'checkWorkRule', icon: '' },
                        //         { id: 41, name: '学生考勤记录', url: '/checkWorkManagement/studentCheckRecord', pid: 26, title: 'studentCheckRecord', icon: '' },
                        //         { id: 41, name: '考勤统计', url: '/checkWorkManagement/checkWorkStatistics', pid: 26, title: 'checkWorkStatistics', icon: '' },
                        //         { id: 41, name: '教师考勤', url: '/checkWorkManagement/teacherCheck', pid: 26, title: 'teacherCheck', icon: '' }
                        //     ]
                        // },
                        // {
                        //     id: 26,
                        //     name: '一卡通消费管理',
                        //     url: '/cardManagement',
                        //     pid: 1,
                        //     icon: 'component',
                        //     title: 'cardManagement',
                        //     child: [
                        //         { id: 41, name: '食堂管理', url: '/cardManagement/canteenManagement', pid: 26, title: 'canteenManagement', icon: '' },
                        //         { id: 41, name: '消费机设备管理', url: '/cardManagement/consumeManagement', pid: 26, title: 'consumeManagement', icon: '' },
                        //         { id: 41, name: '消费记录', url: '/cardManagement/consumeRecord', pid: 26, title: 'consumeRecord', icon: '' },
                        //         { id: 41, name: '充值记录', url: '/cardManagement/rechargeRecord', pid: 26, title: 'rechargeRecord', icon: '' },
                        //         { id: 41, name: '学生饭卡信息', url: '/cardManagement/mealCardInfo', pid: 26, title: 'mealCardInfo', icon: '' }
                        //     ]
                        // },
                        // {
                        //     id: 26,
                        //     name: '缴费管理',
                        //     url: '/payManagement',
                        //     pid: 1,
                        //     icon: 'component',
                        //     title: 'payManagement',
                        //     child: [
                        //         { id: 41, name: '缴费项目管理', url: '/payManagement/payItemsManagement', pid: 26, title: 'payItemsManagement', icon: '' },
                        //         { id: 41, name: '缴费记录', url: '/payManagement/payRecord', pid: 26, title: 'payRecord', icon: '' }
                        //     ]
                        // },
                        // {
                        //     id: 26,
                        //     name: '请假管理',
                        //     url: '/leaveManagement',
                        //     pid: 1,
                        //     icon: 'component',
                        //     title: 'leaveManagement',
                        //     child: [
                        //         { id: 41, name: '学生请假', url: '/leaveManagement/studentLeave', pid: 26, title: 'studentLeave', icon: '' },
                        //         { id: 41, name: '请假审批', url: '/leaveManagement/leaveApprove', pid: 26, title: 'leaveApprove', icon: '' },
                        //         { id: 41, name: '学生请假记录', url: '/leaveManagement/studentLeaveRecord', pid: 26, title: 'studentLeaveRecord', icon: '' },
                        //         { id: 41, name: '教师请假', url: '/leaveManagement/teacherLeave', pid: 26, title: 'teacherLeave', icon: '' },
                        //         { id: 41, name: '教师请假审批', url: '/leaveManagement/teacherLeaveApprove', pid: 26, title: 'teacherLeaveApprove', icon: '' },
                        //         { id: 41, name: '教师请假记录', url: '/leaveManagement/teacherLeaveRecord', pid: 26, title: 'teacherLeaveRecord', icon: '' }
                        //     ]
                        // },
                        // {
                        //     id: 26,
                        //     name: '通知管理',
                        //     url: '/noticeManagement',
                        //     pid: 1,
                        //     icon: 'component',
                        //     title: 'noticeManagement',
                        //     child: [
                        //         { id: 41, name: '学校统计', url: '/payManagement/schoolStatistics', pid: 26, title: 'schoolStatistics', icon: '' },
                        //         { id: 41, name: '成绩发送', url: '/payManagement/scoreSending', pid: 26, title: 'scoreSending', icon: '' }
                        //     ]
                        // },
                        {
                            id: 26,
                            name: '系统设置',
                            url: '/systemManagement',
                            pid: 1,
                            icon: 'peoples',
                            title: 'guide',
                            child: [
                                { id: 41, name: '角色管理', url: '/systemManagement/roleManagement', pid: 26, title: 'roleManagement', icon: '' },
                                { id: 41, name: '用户管理', url: '/systemManagement/userManagement', pid: 26, title: 'userManagement', icon: '' },
                                { id: 41, name: '菜单管理', url: '/systemManagement/accessManagement', pid: 26, title: 'accessManagement', icon: '' }
                            ]
                        }
                    ]
                }]
                const obj = {
                    roles: array1[0].child
                }
                commit('SET_ROLES', array1)
                    // const obj = {
                    //     roles: response.data
                    // }
                    // commit('SET_ROLES', response.data)
                resolve(obj)
            }).catch(error => {
                reject(error)
            })
        })
    },

    // user logout
    logout({ commit, state, dispatch }) {
        return new Promise((resolve, reject) => {
            logout()
                .then(() => {
                    commit('SET_TOKEN', '')
                    commit('SET_ROLES', [])
                    removeToken()
                    resetRouter()
                        // reset visited views and cached views
                        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
                    dispatch('tagsView/delAllViews', null, { root: true })
                    resolve()
                })
                .catch(error => {
                    console.log(error)
                    reject(error)
                })
        })
    },

    // remove token
    resetToken({ commit }) {
        return new Promise(resolve => {
            commit('SET_TOKEN', '')
            commit('SET_ROLES', [])
            removeToken()
            resolve()
        })
    },

    // dynamically modify permissions
    changeRoles({ commit, dispatch }, role) {
        return new Promise(async resolve => {
            const token = role + '-token'

            commit('SET_TOKEN', token)
            setToken(token)

            const { roles } = await dispatch('getInfo')

            resetRouter()

            // generate accessible routes map based on roles
            const accessRoutes = await dispatch('permission/generateRoutes', roles, {
                root: true
            })

            // dynamically add accessible routes
            router.addRoutes(accessRoutes)

            // reset visited views and cached views
            dispatch('tagsView/delAllViews', null, { root: true })

            resolve()
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}